#! /usr/bin/python
# -*- coding: cp1250 -*-

import glob
import re
import sys
import os
import string
import pepe.p_txt.bigtxt as bt
import pepe.p_filesystem.basic as pfb

def srch(OPTIONS='', PATTERN='', FILE=''):
    '''
    Purpose: Search txt files using regex.
    Syntax: srch2 OPTIONS PATTERN FILE
    Example: srch2 -bcr "^ERROR" *.csv

    OPTIONS:
    -b  bare : omit source file name and row number
    -c  count
    -r  recursive
    -v  verbose
    '''
    if 'v' in OPTIONS:
        msg = """:: srch2.py OPTIONS="%s" PATTERN="%s" FILE="%s"\n::"""
        print msg % (OPTIONS, PATTERN, FILE)
    if 'r' in OPTIONS:
        files = pfb.fslist(root='.', patterns=FILE,
                           recurse=True, return_folders=False)
    else:
        files = glob.glob(FILE)

    c = 0
    for infile in sorted(files):
        lino = 0
        for line in bt.lines(infile):
            lino += 1
            if re.search(PATTERN, line):
                if 'c' in OPTIONS:
                    c += 1
                else:
                    if 'b' in OPTIONS:
                        print line,
                    else:
                        print string.ljust(infile+'::'+str(lino)+'::', 70)+line,
    if 'c' in OPTIONS: print "Matched: " + str(c)
    return 1

if __name__ == '__main__':

    if len(sys.argv) == 4:

        import pepe.p_win32.getOsVersion as pwg
        if pwg.main() == 'MS Windows XP, SP2, v5.1, 32bit':
			os.system('@chcp 1250')

        srch(sys.argv[1], sys.argv[2], sys.argv[3])
    elif len(sys.argv) == 3:
        os.system('@chcp 1250')
        srch(OPTIONS='', PATTERN=sys.argv[1], FILE=sys.argv[2])
    else:
        print srch.__doc__

    #print srch.__doc__
    #srch("-", "^import", "*.py")
